/*
 * Copyright (c) 2009 by unreserved.org.
 * All rights reserved.
 */

package org.unreserved.ladderplot;

//XXX: split out HTML encoding (or something)...

/**
 * Encodes strings for use in a particular context.
 */
public class HtmlStringEncoder implements StringEncoder {
    protected String id;
    
    private HtmlStringEncoder() {
    }
    
    private HtmlStringEncoder(String id) {
        this.id = id;
    }
    
    public String encode(String s) {
        StringBuffer sb = null;
        for (int i = 0; i < s.length(); i++) {
            String replacement;
            int c = s.charAt(i);
            switch (c) {
            case '&':
                replacement = "&amp;";
                break;
            case '<':
                replacement = "&lt;";
                break;
            case '>':
                replacement = "&gt;";
                break;
            default:
                if (sb != null) {
                    sb.append((char) c);
                }
                continue;
            }
            if (sb == null) {
                sb = new StringBuffer(s.length() + 20);
                sb.append(s.substring(0, i));
            }
            sb.append(replacement);
        }
        
        s = (sb == null ? s : sb.toString());
        
        if (id == null) {
            return s;
        } else {
            return "<a href=\"javascript:toggleVisible(document.getElementById('" +
                id + "'))\">" + s + "</a>";
        }
    }
    
    public static void main(String[] args) {
        System.out.println("" + new HtmlStringEncoder().encode(args[0]));
    }
}
